<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <title>无敌暴龙大法师</title>
    <meta name="keywords" content="ai助手,对话机器人,人工智能">
    <meta name="description" content="本页面是ai对话助手机器，接入了通义千问，chatgpt等模型">
    <div th:replace="tools/_fragments-tools::basicrefrence"></div>
    <script type="text/javascript" src="/js/jquery.cookie.js"></script>
    <script type="text/javascript" src="/js/showdown.min.js"></script>
    <style>
        .ui.segment.scrolling.always-scroll {
            overflow-y: scroll;
        }
    </style>
</head>
<body>

<nav th:replace="tools/_fragments-tools::head"></nav>

<div class="m-tenDistance" style="height: 80%">
    <div class="ui container" style="height: 100%">
        <div class="ui stackable grid" style="height: 100%">
            <!-- 左侧选择栏 -->
            <div class="six wide column">
                <!-- ai模型选择-->
                <div class="ui top attached segment">
                    使用ai模型：&nbsp;
                    <div id="modelSelectDiv" class="ui dropdown">
                        <div class="default text"></div>
                        <input type="hidden" id="aiModel" />
                        <i class="dropdown icon"></i>
                        <div class="menu" id="ai-menu">
                        </div>
                    </div>
                </div>
                <!--            ai对话身份标识-->
                <div class="ui bottom attached segment">
                    一键复制身份标识
                    <button id="copyButton" class="mini ui inverted secondary button">一键复制身份id</button>
                </div>
            </div>

            <!-- 右侧对话框 -->
            <div class="ten wide column" style="height: 100%">
                <div class="ui attached segment scrolling always-scroll content" id="dialogDiv" style="height: 90%">
                </div>
                <div class="ui bottom attached segment" >
                    <div id="promptDiv" class="ui input" style="width: 60%">
                        <input type="text" placeholder="无敌暴力大法师说：“说点什么吧”" id="prompt">
                    </div>
                    <button class="ui primary button" id="query-btn" onclick="submitQuestion()">
                        发送
                    </button>
                </div>
            </div>
        </div>

    </div>
</div>

<script type="text/javascript">
    var prompt = $("#prompt");
    var promptDiv = $("#promptDiv");
    var dialogDiv = $("#dialogDiv");
    // ai模型选择框
    var modelSelectDiv = $("#modelSelectDiv");
    // ai模型
    var aiModel = $("#aiModel");
    // 新对话框
    var newAnswerSegment = null;
    // 身份标识
    var id = $.cookie('AI_IDENTITY_FLAG');
    // markdown转html对象
    var converter = new showdown.Converter();
    var isPhone = $(window).width() < 500;
    // websocket链接地址
    var websocketUrl = "";
    // ajax链接地址
    var ajaxUrl = "";

    // 一键复制
    var copyButton = $('#copyButton');
    copyButton.data('value',id);
    copyButton.on('click', function() {
        let str = id;
        let input = document.createElement("input");
        let body = document.querySelector("body");
        body.append(input);
        input.value = str
        input.select();
        document.execCommand("copy");
        input.remove();
    })

    var websocket = null;
    var websocketPage = null;
    //如果浏览器支持websocket就建立一个websocket，否则提示浏览器不支持websocket

    function createNewDialogueDiv() {
        newAnswerSegment = $("<div ></div>\n");
        let temp = $(
            "<div class=\"ui segment\">\n" +
            "    <span>\n" +
            "    <a class=\"avatar\">\n" +
            "        <img src=\"/images/ai/ai-ai.png\" style=\"height: 30px; width: 30px\">\n" +
            "    </a>\n" +
            "    </span>\n" +
            "        <span class=\"content\">\n" +
            "        <a class=\"author\">无敌暴龙大法师</a>\n" +
            "    </span>\n" +
            "</div>");
        temp.append(newAnswerSegment);
        dialogDiv.append(temp);
    }

    $(function () {
        $.ajax({
            url: '/tools/ai/allAiModel',
            type: 'post',
            success: function (resp) {
                let modelList = resp.data;
                for(let i = 0; i < modelList.length; i++){
                    $("#ai-menu").append("<div class=\"item\" data-value=\"" + modelList[i].model +"\">\n" +
                        "                            <img class=\"ui avatar image\" src=\"" + modelList[i].logo + "\">\n" +
                        "                            " + modelList[i].name + "\n" +
                        "                        </div>");
                }
                dialogDiv.scrollTop(dialogDiv.prop('scrollHeight'));
                $('.dropdown').dropdown('set selected', 'qwen');
            }});
        $.ajax({
            url: '/tools/ai/aiDialogueSocketUrl',
            type: 'get',
            success: function (resp) {
                if (resp.code === 0) {
                    alert("无法连接到服务器");
                    return;
                }
                websocketUrl = resp.data;
                if('websocket' in window){
                    websocketPage = new WebSocket(websocketUrl + id);
                }else{
                    alert('浏览器不支持，请尝试更换浏览器，尝试更换后失败请联系管理员');
                }
                //建立websocket时自动调用
                websocketPage.onopen = function (event) {
                    // console.log('建立连接');
                }
                //关闭webscoket时自动调用
                websocketPage.oncolse = function (event){
                    alert("连接即将关闭，如果您不想关闭对话连接，请刷新页面重新连接到服务器");
                }
                //websocket接收到消息时调用
                websocketPage.onmessage = function (event){
                    // console.log('收到消息：' + event.data);
                    if (newAnswerSegment == null) {
                        createNewDialogueDiv();
                    }
                    newAnswerSegment.html(converter.makeHtml(event.data));
                    dialogDiv.scrollTop(dialogDiv.prop('scrollHeight'));
                }
                //websocket出错自动调用
                websocketPage.onerror = function () {
                    alert('websocket出错');
                }
                //关闭窗口前关闭websocket连接
                window.onbeforeunload = function (){
                    websocketPage.close();
                }
            }});
        // 移动到对话框（手机上会出现）进入后不正对对话框的情况
        $(window).scrollTop($(document).height());
        prompt.focus();
    })

    function addDialog(avatar, who, dialog) {
        dialogDiv.append("<div class=\"ui segment\">\n" +
            "                    <span>\n" +
            "                    <a class=\"avatar\">\n" +
            "                        <img src=\"/images/ai/" + avatar + "\" style=\"height: 30px; width: 30px\">\n" +
            "                    </a>\n" +
            "                </span>\n" +
            "                    <span class=\"content\">\n" +
            "                    <a class=\"author\">" + who + "</a>\n" +
            "                </span>\n" +
            "                    <div>\n" +
            "                        " + dialog + "\n" +
            "                    </div>\n" +
            "                </div>");
        dialogDiv.scrollTop(dialogDiv.prop('scrollHeight'));
    }
    function submitQuestion(){
        let model = aiModel.val();
        let value = prompt.val();
        if (value == null || value.length === 0) {
            return;
        }
        // 禁用输入
        prompt.val("");
        promptDiv.attr("class","ui disabled input");
        prompt.blur();
        prompt.attr("placeholder", "无敌暴龙大法师说：\"等我说完\"");
        modelSelectDiv.attr("class", "ui disabled dropdown");
        addDialog("ai-me.jpg","我", value);
        // if (model === "qwen"){
        createNewDialogueDiv();
        dialogDiv.scrollTop(dialogDiv.prop('scrollHeight'));
        // }
        if (ajaxUrl == null || ajaxUrl.lengt === 0) {
            newAnswerSegment.html("无法连接到对话服务器");
        }
        if (model === 'wanx') {
            newAnswerSegment.html("<div class=\"ui active dimmer\">\n" +
                "    <div class=\"ui text loader\">图像生成中，请耐心等待</div>\n" +
                "  </div>");
        }
        $.ajax({
            url: "/tools/ai/submitQuestion",
            type: 'post',
            data: {
                model: model,
                prompt: value
            },
            success: function (res) {
                console.log(res);
                if (res.code === 0) {
                    newAnswerSegment.html(res.msg);
                }
                if (res.code === 444) {
                    newAnswerSegment.empty();
                    newAnswerSegment.append("<img width='512px' height='512px' src='"+res.data+"'/>");
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                newAnswerSegment.html("ai对话请求出错，状态码：" +
                    XMLHttpRequest.status +
                    "状态为：" +
                    XMLHttpRequest.readyState +
                    "错误信息：" +
                    textStatus);
            },
            complete:function(xhr,status){
                let newAnswerHtml = newAnswerSegment.html();
                if (newAnswerHtml == null || newAnswerHtml.length === 0) {
                    newAnswerSegment.html("未能获取到对话响应结果，请刷新重试");
                }
                promptDiv.attr("class","ui input");
                prompt.attr("placeholder", "无敌暴力大法师说：“说点什么吧”");
                modelSelectDiv.attr("class", "ui dropdown");
                if(!isPhone){
                    prompt.focus();
                }
                dialogDiv.scrollTop(dialogDiv.prop('scrollHeight'));
            }
        });
    }

    /**
     * 文本框提交功能
     */
    prompt.on("keypress ",function(event) {
        if (event.which === 13) {
            submitQuestion();
        }
    });

    aiModel.on("change", function() {
        let model = aiModel.val();
        // console.log(model);
        dialogDiv.empty();
        addDialog("ai-ai.png","无敌暴龙大法师", "通义万象图像生成模型api未实现连续对话功能\n站长的openai账号被禁封，gpt系列模型暂时无法使用");
        $.ajax({
            url: '/tools/ai/historyDialogues',
            type: 'post',
            data: {
                model: model
            },
            success: function (res) {
                let ai_dialogues = res.data;
                for(let i = 0; i < ai_dialogues.length; i++) {
                    let ai_dialogue = ai_dialogues[i];
                    if(ai_dialogue.role === "assistant") {
                        addDialog("ai-ai.png","无敌暴龙大法师", converter.makeHtml(ai_dialogue.content));
                    }else {
                        addDialog("ai-me.jpg","我", converter.makeHtml(ai_dialogue.content));
                    }
                }
            }
        });
    })
</script>

</body>
</html>